var selectAddrId=undefined;//地址id
var shoppingList=undefined;
var xxShippingMethod=undefined;//默认物流实体存储
jQuery(document).ready(function() {
	var addrId=parseURL(window.location.search).addrId;
	    //监听微信返回按钮
	        pushHistory(addrId);
	        window.addEventListener("popstate", function(e) {  //回调函数中实现需要的功能
	        //alert("我监听到了浏览器的返回按钮事件啦");
	        window.location.href=getRealPath()+"/shopcart.html";  //在这里指定其返回的地址
	    }, false);

	//用户登录然后异步请求获取地址等信息
	loginInfo(function(userInfo){
		if(userInfo==undefined||userInfo.id==""||userInfo.id==null||userInfo.id==undefined){
			window.location.href=getRealPath()+"/shopcart.hrml";
			return;
		}
		var memberId=userInfo.id;//用户id
		$.get(getRealPath()+"/xxmember/userAddrList",{id:memberId,addrId:addrId},function(ret){
			if(ret&&ret.code==200){
				var datas=ret.data;
				if(datas!=undefined&&datas.length>0){
					for(var i in datas){
						if(datas[i].is_default==1){//默认地址
							//console.log(datas[i]);
							$("#addressInfo").html(String.formatmodel(templete.getAddressInfoTeml(),datas[i]));
							selectAddrId=datas[i].id;
						}
					}
				}
			}
		},'json');
	});
	//获取物流公司信息
	xxShippingMethodLoad(function getxxShippingMethod(data){
		xxShippingMethod=data;
		//console.log(xxShippingMethod);
		//初始化产品信息
		initProductList();
	})

})

function pushHistory(addrId) {
	var url=getRealPath()+"/cartToOrder.html"
	if(addrId!=undefined){
		url+="?addrId="+addrId;
	}
    var state = {
        title: "",
        url: url
    };
    window.history.pushState(state, state.title, state.url);
}
//初始化商品信息
function initProductList(){
	var shopCartInfo=jQuery.getCookie("shopCartInfo");
	if(shopCartInfo==""){
		window.location.href=getRealPath()+"/shopcart.html";
	}else{
		shopCartInfo= JSON.parse(shopCartInfo);
		$("#productList").html("");
		var totalMoney=0.00; //最终应付价格
		var productTotalMoney=0.00;//商品价格总数
		var expressTotalMoney=0.00;//快递费总计
		var totalQuantity=0;//数量
		shoppingList=[];
		for(var i=0;i<shopCartInfo.length;i++){
			var itemExpressMoney=0.00;//单价快递价格变量
			if(shopCartInfo[i].select==true){
				//计算商品价格
				console.log(shopCartInfo[i]);
				if(!shopCartInfo[i].is_free_shipping){
					//物流价格计算；
					itemExpressMoney=calcuPrice(shopCartInfo[i].weight)*shopCartInfo[i].quantity;

				}
				expressTotalMoney+=itemExpressMoney;
				productTotalMoney+=Number(shopCartInfo[i].price.replace(",",""))*Number(shopCartInfo[i].quantity);
				totalQuantity+=shopCartInfo[i].quantity;
				shoppingList.push(shopCartInfo[i]);
				if(itemExpressMoney.toString().indexOf('.')<0){
					itemExpressMoney+= '.00';
				}
				shopCartInfo[i].itemExpressMoney=itemExpressMoney;
				$("#productList").append(String.formatmodel(templete.getOrderProductTeml(),shopCartInfo[i]));

			}
		}
		totalMoney=formatMoney(productTotalMoney+expressTotalMoney);
		productTotalMoney=formatMoney(productTotalMoney);
		expressTotalMoney=formatMoney(expressTotalMoney);

		var temp={productTotalMoney:productTotalMoney,expressTotalMoney:expressTotalMoney,totalQuantity:totalQuantity};
		$("#totalInfo").html(String.formatmodel(templete.getOrderTotalInfoTeml(),temp));
		$("#totalPrice").text(totalMoney);
	}
}
//物流价格计算 ：这里都是获取默认物流的价格进行计算
function calcuPrice(weight){
	weight = weight*1;
	if(weight==0){
		return 0.00;
	}else{
		var temp=undefined;
			if(xxShippingMethod.first_weight>=weight){//小于首重量
				temp=xxShippingMethod.first_price*1;
			}else{//大于首重价格 物体重量减去首重量然后除以续重之后取整数 所得结果为续重价格
				var continueMoney= Math.ceil((Number(weight)-Number(xxShippingMethod.first_weight))/Number(xxShippingMethod.continue_weight));
				temp=Number(continueMoney)+ Number(xxShippingMethod.first_price);
			}
		return temp;
	}
}
//获取默认物流信息
function xxShippingMethodLoad(backShippingMethod){
	if(xxShippingMethod!=undefined&&xxShippingMethod.id!=undefined){
		  typeof backShippingMethod == "function" && backShippingMethod(xxShippingMethod);
	}else{
		$.get(getRealPath()+"/xxshippingmethod/getDefaultInfo",{},function(ret){
				if(ret&&ret.code==200&&ret.data){
					typeof backShippingMethod == "function" && backShippingMethod(ret.data);
				}else{
					floatNotify.simple("配送方式配置不正确!");
					window.location.href="./shopcart.html";
				}
		},'json');
	}
}
function formatMoney(money){
	var pos_decimal = money.toString().indexOf('.')
	if (pos_decimal < 0)
	{
		money += '.00';
	}
	return money;
}
/**
 * 提交订单
 * @returns
 */
function submitShopCart(){
	if($("#subStatus").val()==1){//已经提交过表单
		return;
	}
	$("#subStatus").val("1");
	//window.location.href="./my/paySuccess.html";
	if(selectAddrId==undefined||selectAddrId==""){
		floatNotify.simple("请选择收获信息！");
		$("#addressInfo li").attr("style","border-bottom: 1px solid red;");
		return;
	}
	$("#loadingToast").attr("style","opacity:1; display: block;");
	/*console.log(selectAddrId);
	console.log(shoppingList);
	console.log($("#memo").val());*/
	for(var i in shoppingList){//去除了不必要提交的数据
		shoppingList[i]={id:shoppingList[i].id,quantity: shoppingList[i].quantity};
	}
	loginInfo(function(userInfo){
		$.post(getRealPath()+"/xxorder/initOrderInfo",{userId:userInfo.id,addrId:selectAddrId,memo:$("#memo").val(),shopList:JSON.stringify(shoppingList)},function(ret){
			if(ret&&ret.code==200){
				//移除购物车已经购买的商品
				var shopCartInfo=jQuery.getCookie("shopCartInfo");
				shopCartInfo=JSON.parse(shopCartInfo);
				var shopCartInfoNormal=[];
				for(var i in shopCartInfo){
					if(shopCartInfo[i].select==false||shopCartInfo[i].select==undefined){//没有购买的商品
						shopCartInfoNormal.push(shopCartInfo[i]);
					}
					if(shopCartInfoNormal.length>0){
						jQuery.setCookie("shopCartInfo",JSON.stringify(shopCartInfoNormal),null);
					}else{
						jQuery.setCookie("shopCartInfo","",-1);
					}
				}
			   $("#loadingToast").attr("style","opacity:0; display: none;");
				floatNotify.simple("提交成功！");
				setTimeout(function(){
					location.replace("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3a59d3c5f923218e&redirect_uri="+getRealPath()+"/my/orderDetail.html?sn="+ret.message+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
	            },2000);
				//window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3a59d3c5f923218e&redirect_uri="+getRealPath()+"/my/orderDetail.html?sn="+ret.message+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
				//window.location.href="./my/paySuccess.html";
			}else{
				 $("#loadingToast").attr("style","opacity:0; display: none;");
				floatNotify.simple("提交失败，请刷新重试！");
			}
		},'json');
	})
}